package com.derbysoft.defender.web;

/**
 * status codes for usage of http request.
 * <p>
 * The HTTP status code series can be retrieved via {@link #series()}.
 */
public enum HttpStatus {

    // 1xxx 服务器消息类，保留扩展
    //PROCESSING(1002, "Processing"),

    // 2xxx 成功
    OK(2000, "Success"),

    // 3xxx 保留扩展


    // 4xxx 业务错误或者不合法信息，比如找不到酒店信息，找不到account，不符合竞价规则等
    PARAMETER_ERROR(4000, "Parameter error"),
    OPERATION_FAIL(4001, "Operation fail"),
    FORBIDDEN(4003, "Authentication failed"),

    // 5xxx 服务器内部错误信息，比如NullPointerException等
    INTERNAL_SERVER_ERROR(5000, "Internal server error");

    private final int code;
    private final String message;

    HttpStatus(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    @Override
    public String toString() {
        return Integer.toString(code);
    }

    /**
     * Returns the HTTP status series of this status code.
     *
     * @see com.derbysoft.defender.web.HttpStatus.Series
     */
    public Series series() {
        return Series.valueOf(this);
    }

    /**
     * Return the enum constant of this type with the specified numeric code.
     *
     * @param statusCode the numeric code of the enum to be returned
     * @return the enum constant with the specified numeric code
     * @throws IllegalArgumentException if this enum has no constant for the specified numeric code
     */
    public static HttpStatus valueOf(int statusCode) {
        for (HttpStatus status : values()) {
            if (status.code == statusCode) {
                return status;
            }
        }

        throw new IllegalArgumentException("No matching constant for [" + statusCode + "]");
    }

    /**
     * Java 5 enumeration of HTTP status series.
     * <p>Retrievable via {@link com.derbysoft.defender.web.HttpStatus#series()}.
     */
    public static enum Series {
        INFORMATIONAL(1),
        SUCCESSFUL(2),
        REDIRECTION(3),
        CLIENT_ERROR(4),
        SERVER_ERROR(5);

        private final int value;

        Series(int value) {
            this.value = value;
        }

        /**
         * Return the integer value of this status series. Ranges from 1 to 5.
         */
        public int value() {
            return this.value;
        }

        private static Series valueOf(HttpStatus status) {
            int seriesCode = status.getCode() / 1000;

            for (Series series : values()) {
                if (series.value == seriesCode) {
                    return series;
                }
            }

            throw new IllegalArgumentException("No matching constant for [" + status + "]");
        }
    }
}
